<?php

/**
 * 用户功能
 * 
 * @version 1.0
 * @date 2013-12-12
 * @author jinyue.wang
 */
class DefaultController extends FController {

    public function accessRules() {
        $config = array(
            'index' => 1
        );
        return ZRole::auth("role", $config);
    }

    public function __common() {
        parent::init();
        if (empty($this->cLoginUser)) {
          $this->redirect($this->createUrl('/site/login'));
        }

        $this->commonScript();
        Yii::app()->clientScript->registerCssFile(THEME_CSS_URL . '/module_Sip.css');
    }

    /**
     * 角色用户
     * 
     * @version 1.0
     * @author jinyue.wang
     * @date 2013-12-12
     */
    public function actionMember() {

        $this->__common();
        
        $s['pageSize'] = Yii::app()->request->getQuery('pageSize');
        $s['roleid'] = Yii::app()->request->getQuery('roleid', '');

        $where = '';
        $where .= $s['roleid'] ? ' WHERE "role_id" =' . $s['roleid'] : "";
        $order = " ORDER BY id ASC";

        $sqlSelect = 'SELECT "id","username","role_id","lastlogin_ip","lastlogin_time","email,realname" FROM "{{user}}" ';
        $sqlCount = 'SELECT count(*) FROM "{{user}}" ';

        $sqlSelect .= $where . $order;
        $sqlCount .= $where . $order;

        $data = Zcommon::getDaoPageList($sqlSelect, $sqlCount, $s['pageSize']);

        $zEdu = new ZEdu();
        $roleObject = $zEdu->_getRoleObject();
        
        $this->title = '角色用户';
        $pageUrl = Yii::app()->request->getUrl();
        $pageUrl = $this->createUrl("/role/default/member");
        $this->render('member', array(
            'data' => isset($data['listDatas']) ? $data['listDatas'] : '',
            'pages' => isset($data['pages']) ? $data['pages'] : '',
            'roleObject'    => $roleObject,
            'pageUrl' => $pageUrl,
            'search' => $s
        ));
    }

    /**
     * 更新用户信息
     * 
     * @version 1.0
     * @author jinyue.wang
     * @date 2013-12-12
     */
    public function actionUpdate() {
        $this->__common();
        $this->layout = "//layouts/main_other";
        
        $zUser = new ZUser();
        //更新用户信息
        if(isset($_POST) && !empty($_POST)){
        
            //更新用户信息
            $data = ZTask::dis_input($_POST);
            
        	$data['username'] = strtolower($data['username']);
            $status = $zUser->_updUserInfo($_POST['uid'],$data);
            $model = User::model()->count(' "username" = \''.$data['username'].'\' AND "id" != '.$data['uid']);
            if(!empty($model)){
            	$this->frameAjaxMessage(null,'该用户名已经存在!');
            	exit;
            }
            $status = $zUser->_updUserInfo($_POST['uid'],$data);
            
            $this->frameAjaxMessage("/role/default/role_user");
            exit;
        }
        
        $uid = $this->request->getParam('uid');

        $userInfo = $zUser->_getUserInfomation($uid);
        if (empty($userInfo)) {
            $this->frameAjaxMessage(null,"该用户不存在！");
            exit;
        }
        
        $school_object = $zUser->_getSchoolObject();

        $zEdu = new ZEdu();
        $subject_object = $zEdu->_getSubjectObject();
        
        $roleObject = $zEdu->_getRoleObject();
        
        $this->render('update',array(
            'uid'               => $uid,
            'userInfo'          => $userInfo,
            'school_object'     => $school_object,
            'subject_object'    => $subject_object,
            'role_object'       => $roleObject
        ));
    }
    
    /**
     * 新增用户信息
     * 
     * @author jinyue.wang
     * @version 1.0
     * @date 2013-12-13
     */
    public function actionAdd(){
        $this->__common();
        $this->layout = "//layouts/main_other";
        
        $zUser = new ZUser();
        //更新用户信息
        if(isset($_POST) && !empty($_POST)){
            //更新用户信息
            $data = $_POST;
            $data['username'] = strtolower($data['username']);
            $model = User::model()->find(' "username" = \''.$data['username'].'\'');
            if(!empty($model)){
            	$this->frameAjaxMessage('/role/default/role_user','该用户名已经存在!');
            	  exit;
            }
          
            $status = $zUser->_updUserInfo(0,$data);
            
            $this->frameAjaxMessage("/role/default/role_user");
            exit;
        }
        
        $school_object = $zUser->_getSchoolObject();

        $zEdu = new ZEdu();
        $subject_object = $zEdu->_getSubjectObject();
        
        $roleObject = $zEdu->_getRoleObject();
        
        $this->render('add',array(
            'school_object'     => $school_object,
            'subject_object'    => $subject_object,
            'role_object'       => $roleObject
        ));
    }
    
    /**
     * 删除用户信息
     * 
     * @author jinyue.wang
     * @version 1.0
     * @date 2013-12-13
     */
    public function actionDelete(){
        $this->__common();
        
        $id = $this->request->getParam('id');
        
        $status = 0;
        if($id>0){
            $sql = 'DELETE FROM "{{user}}" WHERE "id" = :id ';
            $result = Yii::app()->db->createCommand($sql);
            $result->bindParam(':id',$id,PDO::PARAM_STR);
            
            $status = $result->execute();
            if($status){
                $dsql = 'DELETE FROM "{{user_school}}" WHERE "user_id" = :id';
                $dresult = Yii::app()->db->createCommand($dsql);
                $dresult->bindParam(':id',$id,PDO::PARAM_STR);
                $dresult->execute();
            }
        }
        echo $status;
    }
    
    
    
    /**
     * 	@ 导出Excel
     * 	@ 2013-12-13
     */
    public function actionImportExcel() {

        $conn = Yii::app()->db;

        $zEdu = new ZEdu();
        $roleObject = $zEdu->_getRoleObject();
        
        $sql = 'SELECT "username","role_id","comment" FROM "{{user}}" ';
        $data = $conn->createcommand($sql)->queryAll();

        if (!empty($data)) {
            
            spl_autoload_unregister(array('YiiBase', 'autoload'));
            include_once(dirname(dirname(dirname(dirname(__FILE__)))) . '/extensions/PHPExcel.php');
            include_once(dirname(dirname(dirname(dirname(__FILE__)))) . '/extensions/PHPExcel/IOFactory.php');

            $objPHPExcel = new PHPExcel();
            $objPHPExcel->setActiveSheetIndex(0)
                    ->setCellValue('A1', '序号')
                    ->setCellValue('B1', '用户名称')
                    ->setCellValue('C1', '用户角色')
                    ->setCellValue('D1', '备注');
            $objPHPExcel->getActiveSheet()->getColumnDimension('A')->setWidth(11);
            $objPHPExcel->getActiveSheet()->getColumnDimension('B')->setWidth(25);
            $objPHPExcel->getActiveSheet()->getColumnDimension('C')->setWidth(30);
            $objPHPExcel->getActiveSheet()->getColumnDimension('D')->setWidth(45);
            $i = 2;
            foreach ($data as $v) {
                $objPHPExcel->setActiveSheetIndex(0)
                        ->setCellValue('A' . $i, ($i - 1))
                        ->setCellValue('B' . $i, $v['username'])
                        ->setCellValue('C' . $i, $roleObject[$v['role_id']]['role_name'])
                        ->setCellValue('D' . $i, $v['comment']);
                $i++;
            }
            $objPHPExcel->setActiveSheetIndex(0);
            $file_nams = "用户信息";
            $file_nams .= ".xls";

            if (preg_match("/MSIE/", $_SERVER["HTTP_USER_AGENT"])) {
                $file_nams = urlencode($file_nams);
                $file_nams = str_replace("+", "%20", $file_nams); // 替换空格
            }
            ob_end_clean();
			header("Content-Type: application/vnd.ms-excel;charset=utf-8");
            header("Content-Disposition: attachment; filename=" . $file_nams);
            header('Cache-Control:must-revalidate,post-check=0,pre-check=0');
            header('Expires:0');
            header('Pragma:public');

            $objWriter = PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel5');
            $objWriter->save('php://output');

            Yii::app()->end();
            spl_autoload_register(array('YiiBase', 'autoload'));
        }
    }
    
    
    
}